
#include "RtBase.h"
#include "RtMutex.h"
//////////////////////////////////////////////////////////////////////
// class CRtMutexBase
//////////////////////////////////////////////////////////////////////

CRtMutexBase::CRtMutexBase()
{
}

CRtMutexBase::~CRtMutexBase()
{
#ifdef RT_WIN32
	::DeleteCriticalSection(&m_Lock);
#else
	int nRet = ::pthread_mutex_destroy(&m_Lock);
	if (nRet != 0)  {
		RT_ERROR_TRACE("CRtMutexBase::~CRtMutexBase, pthread_mutex_destroy() failed! err=" << nRet);
	}
#endif // RT_WIN32
}

RtResult CRtMutexBase::Lock()
{
#ifdef RT_WIN32
	::EnterCriticalSection(&m_Lock);
	return RT_OK;
#else
	int nRet = ::pthread_mutex_lock(&m_Lock);
	if (nRet == 0)
		return RT_OK;
	else {
		//RT_ERROR_TRACE("CRtMutexBase::Lock, pthread_mutex_lock() failed! err=" << nRet);
		return RT_ERROR_FAILURE;
	}
#endif // RT_WIN32
}

RtResult CRtMutexBase::UnLock()
{
#ifdef RT_WIN32
	::LeaveCriticalSection(&m_Lock);
	return RT_OK;
#else
	int nRet = ::pthread_mutex_unlock(&m_Lock);
	if (nRet == 0)
		return RT_OK;
	else {
		RT_ERROR_TRACE("CRtMutexBase::UnLock, pthread_mutex_unlock() failed! err=" << nRet);
		return RT_ERROR_FAILURE;
	}
#endif // RT_WIN32
}

RtResult CRtMutexBase::TryLock()
{
#ifdef RT_WIN32
	BOOL bRet = ::TryEnterCriticalSection(&m_Lock);
	return bRet ? RT_OK : RT_ERROR_FAILURE;
#else
	int nRet = ::pthread_mutex_trylock(&m_Lock);
	return (nRet == 0) ? RT_OK : RT_ERROR_FAILURE;
#endif // RT_WIN32
}


//////////////////////////////////////////////////////////////////////
// class CRtMutexThreadRecursive
//////////////////////////////////////////////////////////////////////

CRtMutexThreadRecursive::CRtMutexThreadRecursive()
{
#ifdef RT_WIN32
	::InitializeCriticalSection(&m_Lock);
#else
	pthread_mutexattr_t mutexattr;
    ::pthread_mutexattr_init(&mutexattr);
    ::pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);

    int nRet = ::pthread_mutex_init(&m_Lock, &mutexattr);
    ::pthread_mutexattr_destroy(&mutexattr);
	if (nRet != 0)  {
		RT_ERROR_TRACE("CRtMutexThreadRecursive::CRtMutexThreadRecursive, pthread_mutex_init() failed! err=" << nRet);
	}
#endif // RT_WIN32
}

CRtMutexThreadRecursive::~CRtMutexThreadRecursive()
{
}


//////////////////////////////////////////////////////////////////////
// class CRtMutexThreadRecursive
//////////////////////////////////////////////////////////////////////

CRtMutexThread::CRtMutexThread()
{
#ifdef RT_WIN32
	::InitializeCriticalSection(&m_Lock);
#else
	pthread_mutexattr_t mutexattr;
    ::pthread_mutexattr_init(&mutexattr);
    ::pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_FAST_NP);
    int nRet = ::pthread_mutex_init(&m_Lock, &mutexattr);
    ::pthread_mutexattr_destroy(&mutexattr);
	if (nRet != 0)  {
		RT_ERROR_TRACE("CRtMutexThread::CRtMutexThread, pthread_mutex_init() failed! err=" << nRet);
	}
#endif // RT_WIN32
}

CRtMutexThread::~CRtMutexThread()
{
}
